<template>
  <view class="container">



    <z-paging class="container" ref="paging" v-model="dataList" @query="queryList">

      <template #top>
        <div style="display: flex; justify-content: center">
          <div style="margin-top: 54rpx" class="btn_con" @click="goToScan">扫码开锁</div>
        </div>

        <div style="margin-top: 60rpx; padding-left: 12rpx; padding-right: 12rpx" v-if="info.equipment.id">
          <div class="card_item">
            <div class="card_top" style="display: flex; justify-content: space-between">
              <div style="display: flex; justify-content: space-between">
                <span style="color: rgba(255, 72, 72, 1)"> {{ info.equipment.device_id || info.equipment.mainname }}
                </span>
              </div>
            </div>

            <div style="
            margin-top: 20rpx;
            display: flex; 
          ">

              <div>{{ info.department.deptname }} {{ info.department.build }}号楼 {{
                info.department.floor }}层</div>
            </div>

            <div style="
            margin-top: 20rpx;
            display: flex;
            justify-content: space-between;
          ">
              <div style="display: flex">
                <div class="cancel_btn">取消</div>
                <div class="open_lock_btn" style="margin-left: 20rpx" @click="unlockDevice">开锁</div>
              </div>
            </div>
          </div>
        </div>
      </template>


      <div style="margin-top: 24rpx; margin-left: 30rpx;" v-if="dataList.length > 0">开锁记录</div>
      <div style="margin-top: 26rpx; margin-left: 30rpx; margin-right: 30rpx;" class="card_item"
        v-for="(item, index) in dataList" :key="index">
        <div class="card_top" style="display: flex; justify-content: space-between">
          <div style="display: flex; justify-content: space-between">
            <span style="color: rgba(255, 72, 72, 1)"> {{ item.device_id }} </span>

            <div style="margin-left: 24rpx;">
              <span>{{ item.user.nickname }}</span>
              <span>{{ item.user.mobile }}</span>
            </div>
          </div>
        </div>
        <div style="
            margin-top: 20rpx;
            display: flex; 
          ">

          <div>{{ item.hospitaldepartments.deptname }} {{ item.hospitaldepartments.build }}号楼 {{
            item.hospitaldepartments.floor }}层</div>
        </div>
      </div>

    </z-paging>
  </view>
</template>

<script>
import dayjs from 'dayjs';
import navbarMixin from '@/common/mixin/navbar.js';
import { getOrderDetail, endOrder, temporaryUnlocking, getDeviceDetail } from '@/api/index.js';
import { getOpenLockRecord, reportOpenLock } from '../../../api';
// AES加密库（需要自行引入或实现）
const CryptoJS = require('crypto-js');
var fun_aes = require('utils/aes.js');

export default {
  data() {
    return {
      // 是否处于无蓝牙状态
      noBluetooth: false,
      tokenCmd: [6, 1, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
      // 扫码结果
      scanCode: '',
      // 扫码类型
      scanType: 'return',

      serviceId: '0000FEE7-0000-1000-8000-00805F9B34FB',
      writeCharId: '000036F5-0000-1000-8000-00805F9B34FB',
      readCharId: '0000FEC9-0000-1000-8000-00805F9B34FB',
      notifyCharId: '000036F6-0000-1000-8000-00805F9B34FB',

      // 锁舌状态
      lockStatus: '',
      // 磁铁状态
      magnetStatus: '',

      // 订单号
      orderNumber: '100545054500000',

      // 设备名称
      deviceName: '',
      // 设备编号
      deviceNumber: '',
      currentDeviceMac: "",
      // 开始时间
      startTime: '',
      // 结束时间
      endTime: '',
      // 收费标准
      chargeStandard: '',
      // 预计金额
      expectedAmount: '',
      // 押金金额
      depositAmount: '',

      orderId: '',

      token: '',

      orderInfo: {},

      equipmentInfo: {},
      info: {},
      dataList: [],
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {


  },
  onUnload() {
    if (this.currentDeviceId) {
      uni.closeBLEConnection({ deviceId: this.currentDeviceId });
    }

    uni.stopBluetoothDevicesDiscovery();
  },
  methods: {

    queryList(pageNo, pageSize) {
      const app = this;

      // 此处请求仅为演示，请替换为自己项目中的请求
      getOpenLockRecord({ page: pageNo, limit: pageSize, hospitals_id: uni.getStorageSync("curHospital"), }).then(res => {

        console.log("resresres", res)
        app.total = res.total;

        // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
        app.$refs.paging.complete(res.list);
      }).catch(res => {
        console.log('res', res);

        // 如果请求失败写this.$refs.paging.complete(false)，会自动展示错误页面
        // 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
        // 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
        app.$refs.paging.complete(false);
      })
    },
    // AES加密
    encryptData(data) {
      try {
        const aesKey = [
          0x3a, 0x60, 0x43, 0x2a, 0x5c, 0x01, 0x21, 0x1f, 0x29, 0x1e, 0x0f,
          0x4e, 0x0c, 0x13, 0x28, 0x25,
        ];
        const keyBytes = CryptoJS.enc.Utf8.parse(new Int8Array(aesKey));
        const dataBytes = CryptoJS.enc.Utf8.parse(data);
        // AES-128 ECB模式加密，无填充
        const encrypted = CryptoJS.AES.encrypt(dataBytes, keyBytes, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.NoPadding,
        });

        // 返回Uint8Array
        return new Int8Array(encrypted.ciphertext.words);
      } catch (e) {
        console.error('加密失败:', e);
        return null;
      }
    },
    aesEncrypt: function (array) {
      const INITIAL_KEY = [
        0x3a, 0x60, 0x43, 0x2a, 0x5c, 0x01, 0x21, 0x1f, 0x29, 0x1e, 0x0f, 0x4e,
        0x0c, 0x13, 0x28, 0x25,
      ];

      var acontent = array;
      var contentWA = fun_aes.CryptoJS.enc.int8array.parse(acontent);

      const key = fun_aes.CryptoJS.enc.int8array.parse(INITIAL_KEY);

      const encrypted = fun_aes.CryptoJS.AES.encrypt(contentWA, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.NoPadding,
      });

      var bv = fun_aes.CryptoJS.enc.int8array.stringify(encrypted.ciphertext);

      return bv;
    },
    // 解析广播数据
    parseAdvertData(buffer) {
      try {
        if (!buffer || buffer.byteLength < 9) return null;

        const dataView = new DataView(buffer);
        // 前2字节是PRO
        const PRO = dataView.getUint16(0, false).toString(16).padStart(4, '0');
        // 接下来6字节是MAC地址
        const MAC = Array.from({ length: 6 }, (_, i) =>
          dataView
            .getUint8(2 + i)
            .toString(16)
            .padStart(2, '0'),
        ).join(':');
        // 第9字节是电量(0-100)
        const POWER = dataView.getUint8(8);
        // 第10字节是锁状态(如果有)
        const LOCK_STATE = buffer.byteLength > 9 ? dataView.getUint8(9) : null;

        return { PRO, MAC, POWER, LOCK_STATE };
      } catch (e) {
        console.error('解析广播数据失败:', e);
        return null;
      }
    },
    // 扫描设备
    scanDevices() {
      console.log('开始扫描设备...');
      this.devices = [];
      uni.startBluetoothDevicesDiscovery({
        services: ['FEE7'],
        success: (res) => {
          console.log('扫描已启动', res);

          // 3秒后自动停止扫描
          // setTimeout(() => {
          //   uni.stopBluetoothDevicesDiscovery();
          //   console.log("扫描已停止");
          // }, 15000);
        },
        fail: (err) => {
          console.log('扫描失败: ' + JSON.stringify(err));
          console.log('errerr', err);
        },
      });
    },
    // 初始化蓝牙适配器
    initBluetooth() {
      const that = this;
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log('蓝牙适配器初始化成功');
          that.listenBluetoothEvents();

          setTimeout(() => {
            // 开始扫描
            that.scanDevices();
          }, 500);
        },
        fail: (err) => {
          console.log('蓝牙适配器初始化失败: ' + JSON.stringify(err));
          // uni.showToast({
          //   title: "请打开蓝牙后重新扫码",
          //   icon: "none",
          // });
          that.noBluetooth = true;
        },
      });
    },
    arrayBufferToHexString: function (buffer) {
      if (buffer != '[object ArrayBuffer]') {
        return;
      }
      let dataView = new DataView(buffer);

      var hexStr = '';
      for (var i = 0; i < dataView.byteLength; i++) {
        var str = dataView.getUint8(i);
        var hex = (str & 0xff).toString(16);
        hex = hex.length === 1 ? '0' + hex : hex;
        hexStr += hex;
      }

      return hexStr.toUpperCase();
    },
    // 监听蓝牙事件
    listenBluetoothEvents() {
      console.log('开始监听蓝牙事件');

      // 监听蓝牙适配器状态变化
      // uni.onBluetoothAdapterStateChange((res) => {});

      // 监听设备发现事件
      uni.onBluetoothDeviceFound(async (res) => {
        console.log('resresresres', res);

        res.devices.forEach((device) => {
          if (!device.advertisData) return;

          // 解析广播数据
          // const parsedData = this.parseAdvertData(device.advertisData);

          var macAddressTmp = this.arrayBufferToHexString(device.advertisData);

          var tmpLength = macAddressTmp.length;

          if (tmpLength >= 16) {
            var macAddress =
              macAddressTmp.substring(4, 6) +
              ':' +
              macAddressTmp.substring(6, 8) +
              ':' +
              macAddressTmp.substring(8, 10) +
              ':' +
              macAddressTmp.substring(10, 12) +
              ':' +
              macAddressTmp.substring(12, 14) +
              ':' +
              macAddressTmp.substring(14, 16);
          }



          if (macAddress === this.currentDeviceMac) {
            console.log('找到对应的蓝牙设备拉', {
              macAddress,
              device: device,
            });

            this.currentDeviceId = device.deviceId;

            // 开始连接
            this.connectDevice(device.deviceId);
          }
        });
      });
    },
    // bleGetToken: async function () {
    //   //命令格式
    //   console.log("开始获取token");

    //   //0x06	0x01	0x01	0x01
    //   const _token = [];
    //   const _that = this;
    //   for (let i = 0; i < _that.tokenCmd.length; i++) {
    //     if (i <= 3) {
    //       //
    //       _token.push(_that.tokenCmd[i]);
    //       continue;
    //     }
    //     const _num = Math.round(Math.random() * 100);
    //     _that.tokenCmd.splice(i, 1, _num);
    //     _token.push(_num);
    //   }

    //  await _that.commDevice(_token);
    // },
    bleGetToken: async function () {
      // 命令格式
      console.log('开始获取token');

      // 0x06	0x01	0x01	0x01
      const _token = [];
      const _that = this;
      for (let i = 0; i < _that.tokenCmd.length; i++) {
        if (i <= 3) {
          _token.push(_that.tokenCmd[i]);
          continue;
        }
        const _num = Math.round(Math.random() * 100);
        _that.tokenCmd.splice(i, 1, _num);
        _token.push(_num);
      }

      _that.commDevice(_token);

      // 添加重试机制，最多重试3次
      // let retryCount = 0;
      // const maxRetries = 3;

      // while (retryCount < maxRetries) {
      //   try {
      //     // 设置5秒超时
      //     const timeoutPromise = new Promise((_, reject) => {
      //       setTimeout(() => reject(new Error('timeout')), 5000);
      //     });

      //     // 执行commDevice并等待结果
      //     await Promise.race([_that.commDevice(_token), timeoutPromise]);

      //     // 如果成功执行，跳出循环
      //     console.log(`Token获取成功，尝试次数: ${retryCount + 1}`);
      //     break;
      //   } catch (error) {
      //     retryCount++;
      //     console.log(`Token获取失败，第${retryCount}次重试`, error);

      //     if (retryCount >= maxRetries) {
      //       throw new Error(`获取Token失败，已重试${maxRetries}次`);
      //     }

      //     // 可选：在重试前稍作延迟
      //     await new Promise((resolve) => setTimeout(resolve, 1000));
      //   }
      // }
    },
    // AES解密
    decryptData(data) {
      var that = this;
      var acontent = data;
      // 将密文转换成WordArray
      var contentWA = fun_aes.CryptoJS.enc.int8array.parse(acontent);
      // 插件要求密文是base64格式
      var dcBase64String = contentWA.toString(fun_aes.CryptoJS.enc.Base64);

      const INITIAL_KEY = [
        0x3a, 0x60, 0x43, 0x2a, 0x5c, 0x01, 0x21, 0x1f, 0x29, 0x1e, 0x0f, 0x4e,
        0x0c, 0x13, 0x28, 0x25,
      ];

      const key = fun_aes.CryptoJS.enc.int8array.parse(INITIAL_KEY);

      // 解密 选定mode是CFB类型，无偏移量
      var decrypted = fun_aes.CryptoJS.AES.decrypt(dcBase64String, key, {
        // iv: that.globalData.bleVariable.ivWA,
        mode: fun_aes.CryptoJS.mode.ECB,
        padding: fun_aes.CryptoJS.pad.NoPadding,
      });
      console.log('解密了，内容是=== ' + decrypted);
      // 将解密后的明文转回int8数组
      var bv = fun_aes.CryptoJS.enc.int8array.stringify(decrypted);
      return bv;
    },

    // 等待Token响应
    waitForTokenResponse(timeout) {
      return new Promise((resolve) => {
        let timer;

        // 临时监听Token响应
        const handler = (res) => {
          console.log('接受token相应', res.value);

          const result = res.value;
          var resultArray = new Int8Array(result);

          const decrypted = this.decryptData(resultArray);

          console.log('接受到蓝牙的回调了哈', decrypted);

          if (!decrypted) return;

          // 检查是否为Token响应 (0x06 0x02)
          if (decrypted[0] == 6 && decrypted[1] == 2) {
            const _token = decrypted.slice(3, 7);

            clearTimeout(timer);
            uni.offBLECharacteristicValueChange(handler);

            // this.getDeviceBattery(_token);
            this.queryLockStatus(_token);

            this.token = _token;
            resolve(_token); // 提取4字节Token
          } else if (
            decrypted[0] == 2 &&
            decrypted[1] == 2 &&
            decrypted[2] == 1
          ) {
            // 电量回调
            console.log('获取到电量了', decrypted[3]);

            this.batteryPercentage = decrypted[3];

            reportPower({
              device_code: this.scanCode,
              battery_level: decrypted[3],
            });
          } else if (
            decrypted[0] == 5 &&
            decrypted[1] == 15
            // &&
            // decrypted[2] == 2
          ) {
            // 获取锁状态
            console.log('获取锁状态了', decrypted);

            // resolve(decrypted);

            this.magnetStatus = decrypted[3] == 1;
            // 1标示关锁，0开锁
            this.lockStatus = decrypted[4] == 1;
          }
        };

        uni.onBLECharacteristicValueChange(handler);

        // 设置超时
        timer = setTimeout(() => {
          uni.offBLECharacteristicValueChange(handler);
          resolve(null);
        }, timeout);
      });
    },
    async lockDevice() {
      let _locakCmd = [5, 12, 1, 1];

      this.token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      return this.commDevice(_locakCmd, 'lockDevice');
    },

    // 连接设备
    connectDevice(deviceId) {
      if (!deviceId) {
        console.log('请先选择设备');
        return;
      }

      uni.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
          this.getDeviceServices();
          console.log('连接成功', res);
        },
        fail: (err) => { },
      });
    },
    // 获取设备服务
    getDeviceServices() {
      const _that = this;
      uni.getBLEDeviceServices({
        deviceId: this.currentDeviceId,
        success: (res) => {
          this.getDeviceCharacteristics();

          console.log('获取蓝牙设备所有服务(service)', res);
        },
        fail: (err) => {
          console.log('获取服务失败: ' + JSON.stringify(err));
        },
      });
    },
    // 获取特征值
    getDeviceCharacteristics() {
      const _that = this;
      uni.getBLEDeviceCharacteristics({
        deviceId: this.currentDeviceId,
        serviceId: this.serviceId,
        success: (res) => {
          wx.onBLECharacteristicValueChange(function (characteristic) {
            console.log('监听特征值变化', characteristic);
          });

          wx.notifyBLECharacteristicValueChange({
            deviceId: this.currentDeviceId,
            serviceId: this.serviceId,
            characteristicId: this.notifyCharId,
            state: true,
            success: (res) => {
              console.log('已启用通知', res);

            },
            fail: (err) => {
              console.log('启用通知失败: ' + JSON.stringify(err));
            },
            complete: (res) => {
              uni.onBLECharacteristicValueChange((res) => {
                console.log('接收到数据', res);
              });
              _that.getToken();
              setTimeout(() => {
                _that.bleGetToken();
              }, 500);
            },
            type: 'notification',
          });
        },
        fail: (err) => { },
      });
    },

    async unlockDevice() {

      const app = this;

      // 如果处于有蓝牙状态且没有token，则提示用户重新获取token
      if (!this.noBluetooth && !this.token) {
        return uni.showToast({
          title: '蓝牙正在连接设备中，请重试',
          icon: 'none',
        });

      }

      // 如果是没开蓝牙，并且是NB锁
      if (this.noBluetooth && this.equipmentInfo.hardware_type == 2) {
        temporaryUnlocking({
          equipment_id: this.info.equipment.id,
          equipment_info_id: this.info.equipment_info.id
        });

        return uni.showModal({
          title: "提示",
          content: "点击唤醒按钮即可开锁",
          showCancel: false,
          confirmText: "确定",
        })
      }

      // 如果是没开蓝牙，如果是1拖5
      if (this.equipmentInfo.hardware_type == 3) {
        temporaryUnlocking({
          equipment_id: this.info.equipment.id,
          equipment_info_id: this.info.equipment_info.id
        });

        return uni.showModal({
          title: "提示",
          content: "点击唤醒按钮即可开锁",
          showCancel: false,
          confirmText: "确定",
        })
      }

      if (this.equipmentInfo.hardware_type === 2 || this.equipmentInfo.hardware_type === 1) {
        this.$nextTick(async () => {
          let _locakCmd = [5, 1, 6];

          for (let i = 0; i <= 5; i++) {
            _locakCmd.push(48);
          }

          this.token.forEach((item) => {
            _locakCmd.push(item);
          });

          // 三个随机数
          for (let i = 0; i < 3; i++) {
            const _num = Math.round(Math.random() * 100);
            _locakCmd.push(_num);
          }

          const encrypted = this.aesEncrypt(_locakCmd);
          if (!encrypted) {
            throw new Error('加密失败');
          }

          try {
            await this.writeBLEValue(encrypted.buffer);
          } catch (error) {

          }
        })
      } else if (_that.equipmentInfo.hardware_type == 3) {
        this.$nextTick(async () => {
          app.fiveUnlockDevice()
        })

      }

      this.reportOpenLockFn(this.scanCode)

    },

    async lockDevice() {
      let _locakCmd = [5, 12, 1, 1];

      this.token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      const encrypted = this.aesEncrypt(_locakCmd);
      if (!encrypted) {
        throw new Error('加密失败');
      }

      await this.writeBLEValue(encrypted.buffer);
    },
    // 获取设备电量
    async getDeviceBattery(token) {
      let _locakCmd = [2, 1, 1, 1];

      token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      this.commDevice(_locakCmd, 'getDeviceBattery');
    },
    // 查询锁状态
    async queryLockStatus(token) {
      let _locakCmd = [5, 14, 1, 1];

      token.forEach((item, index) => {
        _locakCmd.push(item);
      });

      for (let i = 0; i <= 7; i++) {
        _locakCmd.push(Math.round(Math.random() * 100));
      }

      await this.commDevice(_locakCmd, 'queryLockStatus');
    },

    // 封装BLE写入操作
    writeBLEValue(value) {
      return new Promise((resolve, reject) => {
        uni.writeBLECharacteristicValue({
          deviceId: this.currentDeviceId,
          serviceId: this.serviceId,
          characteristicId: this.writeCharId,
          value: value,
          success: resolve,
          fail: reject,
        });
      });
    },
    // 通过设备id去创建订单
    async getOrderInfo() {

      // const status = this.scanType === 'view' ? 3 : 1;

      try {
        const _res = await getDeviceDetail({
          equipment_info_id: this.scanCode,
        });


        if (_res?.equipment?.hospitals_id != uni.getStorageSync("curHospital")) {
          return
        }

        console.log('_res_res_res', _res);

        this.info = _res


        // this.orderId = _res?.order?.id;

        this.currentDeviceMac = _res?.equipment_info?.mac;

        // this.orderInfo = _res.order;

        this.equipmentInfo = _res.equipment;

        this.deviceName = _res.equipment_info.devicename;
        this.deviceNumber = _res.equipment_info.deviceno;

        return _res;

      } catch (error) { }
    },
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },
    async fiveUnlockDevice() {
      let _locakCmd = [5, 129, 9];

      let temp = [];

      if (this.equipmentInfoObj.nb_number == 1) {
        temp = [1, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 2) {
        temp = [2, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 3) {
        temp = [4, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 4) {
        temp = [8, 0, 0];
      } else if (this.equipmentInfoObj.nb_number == 5) {
        temp = [10, 0, 0];
      }

      /* 密码 */
      for (let i = 0; i <= 5; i++) {
        _locakCmd.push(48);
      }
      /* 掩码 */
      temp.forEach((item) => {
        _locakCmd.push(item);
      });

      this.token?.forEach((item) => {
        _locakCmd.push(item);
      });

      console.log('1拖5开锁 => ', _locakCmd);

      const encrypted = this.aesEncrypt(_locakCmd);
      if (!encrypted) {
        throw new Error('加密失败');
      }

      await this.writeBLEValue(encrypted.buffer);

      // const result = await this.waitCloseLock(50000);
    },
    async getToken() {
      try {

        const token = await this.waitForTokenResponse(500000);
        if (token) {
          this.token = token;
          // this.addLog(`获取Token成功: ${this.bytesToHex(this.token)}`);
        } else {
          throw new Error("获取Token超时");
        }


      } catch (err) {

        this.token = null;
      }
    },

    /**
     * 与设备交互
     */
    commDevice: async function (cmd) {
      // return _data;
      const encrypted = this.aesEncrypt(cmd);

      await this.writeBLEValue(encrypted.buffer);
      return

      return new Promise(async (resolve, reject) => {
        const encrypted = this.aesEncrypt(cmd);

        await this.writeBLEValue(encrypted.buffer);
        // 等待Token响应 (超时5秒)
        const _data = await this.waitForTokenResponse(10000);
        console.log('获取到蓝牙的回调了', _data);
        if (_data) {
          resolve(_data);
        } else {
          reject('获取蓝牙回调超时');
        }
      });
    },

    // 上报开锁记录
    async reportOpenLockFn(equipment_info_id) {
      try {
        await reportOpenLock({
          equipment_info_id
        })
      } catch (error) {

      }
    },
    async goToScan() {
      const app = this;
      uni.scanCode({
        scanType: ["qrCode", "barCode"],
        async success(res) {
          console.log('res.result', res.result);

          const code = encodeURIComponent(
            res?.result?.split("kpl/")?.[1])

          app.scanCode = code;


          app.$nextTick(async () => {
            const _res = await app.getOrderInfo();

            if (_res?.equipment?.hospitals_id != uni.getStorageSync("curHospital")) {
              uni.showToast({
                title: "当前设备不属于您当前操作医院，无法开锁",
                icon: "none",
              });

              return;
            }

            console.log('reee', _res);

            app.initBluetooth();
          });

        },
        fail(err) {
          if (err.errMsg.includes("cancel")) {
            return;
          }
          uni.showToast({
            title: "扫码失败，请重试",
            icon: "none",
          });
        },
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #ebebeb;
}

.btn_con {
  width: 624rpx;
  height: 98rpx;
  line-height: 50rpx;
  border-radius: 42rpx;
  background: linear-gradient(92.01deg,
      rgba(87, 215, 130, 1) 38.63%,
      rgba(29, 221, 94, 1) 80.23%);
  color: rgba(255, 255, 255, 1);
  font-size: 36rpx;
  text-align: center;
  box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(87, 215, 130, 1);
  font-family: PingFangSC-regular;

  display: flex;
  justify-content: center;
  align-items: center;
}

.card_item {
  padding: 22rpx;

  color: rgba(0, 0, 0, 1);
  font-size: 32rpx;
  text-align: left;
  font-family: PingFangSC-regular;

  background-color: white;
}

.cancel_btn {
  width: 122rpx;
  height: 56rpx;
  line-height: 38rpx;
  border-radius: 8rpx;
  background-color: rgba(156, 156, 156, 1);
  color: rgba(255, 255, 255, 1);
  font-size: 26rpx;
  text-align: center;
  font-family: PingFangSC-regular;

  display: flex;
  justify-content: center;
  align-items: center;
}

// 开锁
.open_lock_btn {
  width: 122rpx;
  height: 56rpx;
  line-height: 38rpx;
  border-radius: 8rpx;
  background-color: rgba(13, 199, 54, 1);
  color: rgba(255, 255, 255, 1);
  font-size: 26rpx;
  text-align: center;
  font-family: PingFangSC-regular;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
